<template>
	<view class="register-container">
		<view>
			<u-navbar :is-back="true" back-icon-color="#000000" 
			title-color="#000000" :title-size="34" 
			title="创建账户" :border-bottom="true" :background="background">
			</u-navbar>	
		</view>
		<view class="u-p-20">
			<view class="u-m-t-60 u-m-b-80">
				<view class="u-text-center u-font-32 u-m-b-20 u-tips-color">设置头像</view>
				<view class="u-flex u-row-center u-col-center">
					<view  class="slot-btn">
						<u-upload ref="imageUpload" 
								image-mode="aspectFill"
								:preview-full-image="true"
								:deletable="true"
								:custom-btn="true" 
								:width="avatarWidth"
								:height="avatarHeight"
								:show-upload-list="showUploadList" 
								name="fileName"  :action="action"
								:header="{'Access-Control-Allow-Origin': '*','TOKEN_IM': 'register'}"
								:multiple="false"  
								:max-size="10 * 1024 * 1024"  :max-count="1"
								:auto-upload="true"  
								:file-list="images"
								@on-uploaded="onUploaded" 
								@on-error="onUpLoadError"
								@on-remove="onRemove"
								@on-preview="onPreview">
							<view slot="addBtn">
								<u-icon name="camera-fill" size="50" color="#ffffff"></u-icon>
							</view>
						</u-upload>
					</view>
				</view>
			</view>
			<u-form :model="newUser" ref="newUser" :label-width="150" label-position="left" 
					:label-style="labelStyle">
						<u-form-item label="昵称" prop="userName">
							<u-input v-model="newUser.userName" :custom-style="customInputStyle"
							placeholder="您的昵称" :placeholder-style="placeholderStyle"
							:input-align="inputAlign"/>
						</u-form-item>
						<u-form-item  label="地区" prop="address" label-position="left">
							<u-input :border="false" type="select" :input-align="inputAlign"
									:placeholder-style="placeholderStyle" :custom-style="customInputStyle"
									 :select-open="pickerShow" v-model="newUser.address" 
									 placeholder="您的所在地" @click="pickerShow = true"></u-input>
						</u-form-item>
						<u-form-item label="手机号" prop="mobile">
							<u-input v-model="newUser.mobile" :custom-style="customInputStyle"
							type="number"
							:placeholder-style="placeholderStyle" placeholder="您的手机号码" 
							:input-align="inputAlign"/>
						</u-form-item>
						<u-form-item label="密码" prop="password">
							<u-input :password-icon="true" type="password" :input-align="inputAlign"
									  v-model="newUser.password"  :custom-style="customInputStyle"
									  :placeholder-style="placeholderStyle" placeholder="您的密码"/>
						</u-form-item>
						<!-- <u-form-item  label="" prop="addressDetail">
							<u-input height="70" maxlength="100"  clearable  type="textarea"  placeholder="请输入您的详细地址" v-model="newUser.addressDetail" />
						</u-form-item> -->
						<!-- <u-form-item label-position="left"  label="验证码" prop="smsCode">
							<u-input :border="false" placeholder="请输入手机验证码" v-model="newUser.smsCode" type="text"></u-input>
							<u-button slot="right" type="success" size="mini" @click="getCode">{{codeTips}}</u-button>
						</u-form-item> -->
			</u-form>
		</view>
		<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
		<u-picker mode="region" v-model="pickerShow" @confirm="regionConfirm"></u-picker>
		<view class="submit-register">
			<!--  :disabled="validateFlag"  plain :ripple="true" ripple-bg-color="#19be6b"   -->
			<u-button  type="success" shape="circle" @click="submitRegist">立即注册</u-button>
		</view>
		<view class="agreement">
			<u-checkbox  active-color="#19be6b" v-model="agreementCheck" @change="agreementCheckChange"></u-checkbox>
			<view class="agreement-text">
				勾选代表同意应用的版权协议
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				background:{
					backgroundColor: '#ffffff',
				},
				labelStyle:{
				  "color":"#000000",
				   "fontSize":"32rpx",
				   "paddingLeft":"10rpx"
				},
				placeholderStyle:"color:#909399;fontSize:32rpx",
				customInputStyle:{
					color:"#000000",
					fontSize:"32rpx",
				},
				inputAlign:"left",
				newUser:{
					userName:'',
					realName:'',
					password:'',
					mobile:'',
					smsCode:'123456',
					address:'',
					avatar:'',
				},
				validateFlag:true,
				pickerShow: false,
				avatarWidth:150,
				avatarHeight:150,
				action: '', // 上传文件地址
				showUploadList:true,
				images:[],
				addressObj:{},
				agreementCheck:false,
				agreement:false,
				codeTips:'',
				rules: {
					userName: [
						{ 
							required: true, 
							message: '请输入您的昵称', 
							trigger: ['change','blur'],
						},
						/* {
							required: true, 
							validator: (rule, value, callback) => {
								return this.$u.test.chinese(value);
							},
							message: '昵称只支持中文',
							trigger: ['change','blur'],
						}, */
					],
					address: [
						{ 
							required: true, 
							message: '请选择地址', 
							trigger: ['change','blur'],
						}
					],
				/* 	addressDetail: [
						{ 
							required: true, 
							message: '请选择地址', 
							trigger: ['change','blur'],
						}
					], */
					mobile: [
						{ 
							required: true, 
							message: '手机号不能为空!', 
							trigger: ['change','blur'],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['change','blur'],
						},
						// 校验用户是否已存在
						{
							asyncValidator: (rule, value, callback) => {
								console.log("校验手机号",value);
								this.$u.api.sys.checkMobile({'mobile':value}).then(res => {
									if(res.code!=200) {
										//'该手机号已经被注册'
										callback(new Error(res.message));
									} else {
										callback();
									}
								})
							},
							trigger: ['blur'],
						}
					],
					smsCode:[
						{
							required: true, 
							message: '验证码不能为空!', 
							trigger: ['change','blur'],
						},
						{
							len:6,
							type:'number',
							message: '验证码有误',
							trigger: ['change','blur'],
						},
					],
					password: [
						{
							required: true, 
							message: '密码不能为空', 
							trigger: ['change','blur'],
						},
						// 正则判断为字母或数字,// 正则不能含有两边的引号
						{
							pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+\S{5,12}$/,
							message: '需同时含有字母和数字，长度在6-12之间',
							trigger: ['change','blur'],
						},
					]
				},
			};
		},
		onLoad() {
			this.action=this.$u.api.multipartAddress.updload+"&dir=userAvatars";	
		},
		onReady() {
			// 得到整个组件对象，内部图片列表变量为"lists"
			this.images = this.$refs.imageUpload.lists;
			this.$refs.newUser.setRules(this.rules);
		},
		methods:{
			onUpLoadError(res,index,lists,name){
			  	console.log("上传异常",res);
			},
			onPreview(url, lists, name){
				console.log("预览图片",url);
				console.log("预览图片",lists)
			},
			onRemove(index, lists, name){
				this.images=[];
			},
			//所有图片上传完毕触发
			onUploaded(list,name){
				let that=this;
				console.log("上传完成",list);
				let files = [];
				list.map((file,index)=>{
					if(file.progress == 100&&file.response){
						let res=file.response;
						let fullPath= res.data.fullPath;
						let fileName=res.data.fileName;
						let target = that.$u.api.multipartAddress.target;
						let imageUrl="";
						if(target=="local"){
							imageUrl=that.$u.api.multipartAddress.showFile+fullPath;
						}
						else{
							imageUrl=fullPath;
						}
						file.url=imageUrl;
						res.data.url=imageUrl;
						files.push(res.data);
					};
				})
				that.images=files;
				console.log("=====上传完成==name==="+name,that.images);
			},
			codeChange(text) {
				this.codeTips = text;
			},
			agreementCheckChange:function(e){
				console.log("是否统一协议",e);
				this.agreement=e.value;
			},
			// 选择地区回调
			regionConfirm(e) {
				this.newUser.address = e.province.label + '-' + e.city.label + '-' + e.area.label;
				this.addressObj=e;
			},
			// 获取验证码
			getCode() {
				if(this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码',
						mask: true
					})
					setTimeout(() => {
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						this.$u.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}, 2000);
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			checkSmsCode:function(smsCode){
				console.log("检验验证码",smsCode);
				return true;
			},
			submitRegist:function(){
				console.log("提交注册");
				let that=this;
				this.$refs.newUser.validate(valid => {
					if (valid) {
						uni.clearStorageSync();
						if(!that.agreement){
							this.globalUtil.utilAlert("请先勾选同意应用协议");
							return;
						}
						let smsCode= that.newUser.smsCode;
						let flag= that.checkSmsCode(smsCode);
						if(flag){
							let addressDetail= that.newUser.addressDetail;
							if(addressDetail!=undefined&&addressDetail.length>0){
								let detail={"label":addressDetail};
								that.addressObj.detail=detail;
							}
							else{
								that.addressObj.detail={"label":""};
							}
							let addressStr=JSON.stringify(that.addressObj);
							let userAvatar=null;
							if(that.images&&that.images.length>0){
								userAvatar=that.images[0].url;
							}
							let param={
								"userName": that.newUser.userName,
								"realName": that.newUser.userName,
								"password": that.newUser.password,
								"mobile": that.newUser.mobile,
								"address": addressStr,
								"userDeviceId":that.vuex_deviceMode,
								"avatar":userAvatar
							};
							this.$u.api.sys.register(param).then(res => {
								if(res.code==200) {
									 this.globalUtil.utilAlert("注册成功");
									 let deviceMode=this.vuex_deviceMode;
									 let loginParam={
										mobile:that.newUser.mobile,
										password:'',
										userDeviceId:deviceMode,
										avatar:userAvatar
									 }
									 this.$u.vuex('vuex_loginParam',loginParam);
									 uni.navigateBack();
									 return;
								} else {
									this.globalUtil.utilAlert("注册失败");
								}
							})
							console.log("验证码校验通过");
						}else{
							this.globalUtil.utilAlert("验证码错误!");
							return;
						}
					} else {
						console.log('验证失败');
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.register-container{
		padding: 0 20rpx;
	}
	.avatar{
		height: 200rpx;
		padding: 50rpx;
		margin-bottom: 0rpx;
		text-align: center;
		border-bottom: 1px solid #EEEEEE;
	}
	.agreement {
		display: flex;
		flex-direction: row;
		align-items: center;
		align-content: center;
		justify-content: center;
		justify-items: center;
		margin: 40rpx 0;
		
		.agreement-text {
			padding-left: 8rpx;
			color: $u-tips-color;
		}
	}
	.submit-register{
		margin: 50rpx;
		margin-top: 25%;
	}
	.slot-btn {
		width: 150rpx;
		height: 150rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: $uni-text-color-disable;
		border-radius: 10rpx;
	}
	
	.slot-btn__hover {
		background-color: rgb(235, 236, 238);
	}
</style>
